import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/pages/information/widget/filter.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/src/slide_panel.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class VideoMonitorDevicePage extends StatefulWidget {
  const VideoMonitorDevicePage({super.key});

  @override
  State<VideoMonitorDevicePage> createState() => _VideoMonitorDevicePageState();
}

class _VideoMonitorDevicePageState extends State<VideoMonitorDevicePage> {
  RefreshController refreshController = RefreshController();
  ListPaginationModel pagination = ListPaginationModel();
  List<dynamic> list = List.filled(10, {}).toList();
  ValueNotifier hasFilter = ValueNotifier<bool>(false);
  PanelController? panelController;
  Map<String, dynamic> filterParams = {};
  String keyword = '';
  fetchData() async {
    var res = await Http.instance.post(
      '/api/information/video_monitor/devices',
      data: {
        'page': pagination.currentPage,
        'keyword': keyword,
        ...filterParams
      },
    );
    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }
    setState(() {});
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      dismissOnCapturedTaps: true,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: UiTheme.of(context).match(light: Colors.white),
          title: const Text('热企视频'),
          actions: [
            IconButton(
              onPressed: () {
                if (panelController?.isPanelOpen == true) {
                  panelController?.close();
                } else {
                  panelController?.open();
                }
              },
              icon: ValueListenableBuilder(
                valueListenable: hasFilter,
                builder: (context, state, widget) {
                  return Icon(state ? UiIcons.filter_fill : UiIcons.filter);
                },
              ),
            ),
          ],
        ),
        body: UiLifeCycle(
            onRouteDone: () {
              fetchData();
            },
            child: FilterView(
              filter: 'video.monitor',
              onCreated: (context, controller, filter) {
                hasFilter.value = filter.state;
                panelController = controller;
              },
              onChange: (filter) {
                hasFilter.value = filter.state;
                setState(() {
                  list = List.filled(20, {}).toList();
                });
                filterParams = filter.params;
                pagination.currentPage = 1;
                fetchData();
              },
              body: Column(
                children: [
                  Container(
                    color: UiTheme.of(context).match(
                      light: Colors.white,
                      dark: Theme.of(context).appBarTheme.backgroundColor,
                    ),
                    padding: const EdgeInsets.only(
                      top: UiTheme.toolbarSpacing,
                      left: UiTheme.spacingX,
                      right: UiTheme.spacingX,
                      bottom: UiTheme.spacingX,
                    ),
                    alignment: Alignment.centerLeft,
                    child: UiSearchBar(
                      backgroundColor:
                          UiTheme.of(context).match(light: Colors.grey[100]),
                      placeholder: '搜索企业名称或者设备机位',
                      onSubmitted: (val) {
                        keyword = val;
                        pagination.currentPage = 1;
                        fetchData();
                      },
                      onClear: () {
                        keyword = '';
                        pagination.currentPage = 1;
                        fetchData();
                      },
                    ),
                  ),
                  const Divider(height: 0),
                  Expanded(
                    child: UiPushToRefresh(
                      controller: refreshController,
                      onRefresh: () {
                        pagination.currentPage = 1;
                        fetchData();
                      },
                      enablePullUp: pagination.lastPage > 1 &&
                          !refreshController.isRefresh,
                      onLoad: () {
                        pagination.currentPage++;
                        fetchData();
                      },
                      child: list.isEmpty
                          ? const Center(child: UiResult())
                          : MasonryGridView.count(
                              padding: const EdgeInsets.all(UiTheme.spacingX),
                              crossAxisCount: 2,
                              mainAxisSpacing: UiTheme.spacingX,
                              crossAxisSpacing: UiTheme.spacingX,
                              itemCount: list.length,
                              itemBuilder: (context, index) {
                                var item = list[index];
                                var isBlock = item['id'] == null;
                                return UiTap(
                                  onTap: () {
                                    if (item['dialog_play'] == true) {
                                      showModalBottomSheet(
                                        context: context,
                                        builder: (context) {
                                          return VideoMonitorPlayView(
                                            item: item,
                                          );
                                        },
                                        clipBehavior: Clip.hardEdge,
                                        shape: const RoundedRectangleBorder(
                                          borderRadius: BorderRadius.vertical(
                                            top: Radius.circular(
                                                UiTheme.boxRadiusX),
                                          ),
                                        ),
                                        useSafeArea: true,
                                        backgroundColor: Colors.black,
                                        isScrollControlled: true,
                                        constraints: BoxConstraints(
                                          maxHeight: MediaQuery.of(context)
                                                  .size
                                                  .height -
                                              kToolbarHeight -
                                              15,
                                        ),
                                      );
                                    } else {
                                      App.push(
                                          '/video/monitor/play?id=${item['id']}&title=${item['name']}');
                                    }
                                  },
                                  child: UiPanel(
                                    padding: const EdgeInsets.all(10),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        ClipRRect(
                                          borderRadius: BorderRadius.circular(
                                              UiTheme.boxRadius),
                                          child: AspectRatio(
                                            aspectRatio: 1,
                                            child: isBlock
                                                ? const UiBlock(
                                                    margin: 0,
                                                  )
                                                : CachedNetworkImage(
                                                    imageUrl: item['image'],
                                                    fit: BoxFit.cover,
                                                  ),
                                          ),
                                        ),
                                        const SizedBox(height: 10),
                                        isBlock
                                            ? const UiBlock(height: 18)
                                            : Text(
                                                item['name'] ?? '',
                                                style: const TextStyle(
                                                  fontSize: 16,
                                                ),
                                              ),
                                        const SizedBox(height: 2),
                                        isBlock
                                            ? const UiBlock(
                                                height: 14,
                                                width: 60,
                                              )
                                            : Row(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.center,
                                                children: [
                                                  const Icon(
                                                    UiIcons.location_fill,
                                                    size: 12,
                                                    color: UiTheme.primary,
                                                  ),
                                                  const SizedBox(width: 3),
                                                  Expanded(
                                                    child: Text(
                                                      item['company_name'] ??
                                                          '',
                                                      style: const TextStyle(
                                                        fontSize: 12,
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                    ),
                  ),
                ],
              ),
            )),
      ),
    );
  }
}

class VideoMonitorPlayView extends StatefulWidget {
  const VideoMonitorPlayView({super.key, this.item});
  final dynamic item;
  @override
  State<VideoMonitorPlayView> createState() => _VideoMonitorPlayViewState();
}

class _VideoMonitorPlayViewState extends State<VideoMonitorPlayView> {
  Map<String, dynamic> video = {};
  @override
  void initState() {
    video = widget.item;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(UiTheme.boxRadiusX),
      child: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          toolbarHeight: 60,
          backgroundColor: Colors.transparent,
          title: Text(
            widget.item['name'],
            style: const TextStyle(color: Colors.white),
          ),
          leading: const CloseButton(),
          foregroundColor: Colors.white,
        ),
        body: DefaultTextStyle(
          style: const TextStyle(color: Colors.white),
          child: SizedBox(
            width: double.infinity,
            height: double.infinity,
            child: SafeArea(
              bottom: true,
              child: Center(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      color: Colors.black,
                      child: UiVideo(
                        autoPlay: true,
                        url: video['play_url'],
                        title: video['name'],
                        isLive: video['is_live'],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
